﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.SqlClient;
using DataAccessLib;
using System.Linq;

namespace ePharmacyLauch
{
    public partial class Dmbd : BaseForm
    {
        private NhaThuocModelDataContext context = new NhaThuocModelDataContext();
        private DataTable table;
        public Dmbd()
        {
            InitializeComponent();
        }

        private void Dmbd_Load(object sender, EventArgs e)
        {
           //don vi
            var dvList = this.context.DonVis.ToList();
            foreach (var dv in dvList)
            {
                this.cbDVT.Properties.Items.Add(dv.TenDonVi);
                this.repComboDVT.Items.Add(dv.TenDonVi);
            }
            this.cbDVT.Text = "Viên";

            //ten thuoc neu co
            var thList = this.context.Thuocs.ToList();
            foreach (var t in thList)
                this.cbTenThuoc.Properties.Items.Add(t.TenThuoc);
            
            //init table
            InitTable();

            FetchDataIntoTable();

            this.cbTenThuoc.Focus();
        }

        private void FetchDataIntoTable()
        {
            var thuocList = (from t in this.context.Thuocs
                            join dv in this.context.DonVis on t.DVT equals dv.Id
                            orderby t.Id ascending
                            select new 
                            {
                                MaThuoc = t.Id, TenThuoc = t.TenThuoc, GhiChu = t.MoTa, dv.TenDonVi, t.Dung
                            }).ToList();
                            
            foreach(var th in thuocList)
            {
                var r = this.table.NewRow();
                r.ItemArray = new object[]{
                    th.MaThuoc, th.TenThuoc, th.GhiChu, th.TenDonVi, th.Dung
                };
                this.table.Rows.Add(r);
            }
            this.table.AcceptChanges();
            this.gvDmbd.DataSource = table;
        }

        private void InitTable()
        {
            this.table = new DataTable("dt");
            this.table.Columns.Add("MaThuoc", typeof(int));
            this.table.Columns.Add("TenThuoc", typeof(string));
            this.table.Columns.Add("GhiChu", typeof(string));
            this.table.Columns.Add("DonVi", typeof(string));
            this.table.Columns.Add("Dung", typeof(bool));

        }

        private void ucBtSave_Click(object sender, EventArgs e)
        {
            DoUpdate();
        }

        private void ucBtXoa_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có muốn xóa những loại thuốc đã chọn?", "Thông báo", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                DoDelete();  
        }

        private void DoDelete() 
        {
            var sel = this.gridView1.GetSelectedRows();
            if (sel == null || sel.Length == 0)
            {
                MessageBox.Show("Xin chọn loại thuốc để xóa");
                return;
            }

            for (int i = 0; i < sel.Length; i++)
            {
                var grow = (DataRowView)this.gridView1.GetRow(sel[i]);
                var maThuoc = (int)grow["MaThuoc"];
                var th = this.context.Thuocs.FirstOrDefault(x => x.Id == maThuoc);
                if (th != null)
                    this.context.Thuocs.DeleteOnSubmit(th);
            }
            this.context.SubmitChanges();

            this.gridView1.DeleteSelectedRows();
            this.table.AcceptChanges();
            this.gvDmbd.DataSource = table;
        }

        private void DoUpdate()
        {
            bool hasChanges = false;
            foreach (DataRow r in this.table.Rows)
            {
                if (r.RowState == DataRowState.Modified) {
                    hasChanges = true;
                    var maThuoc = (int)r["MaThuoc"];
                    var th = this.context.Thuocs.FirstOrDefault(x => x.Id == maThuoc);
                    if (th != null) {
                        th.TenThuoc = r["TenThuoc"].ToString().Trim();
                        th.Dung = (bool)r["Dung"];
                        th.MoTa = r["GhiChu"].ToString().Trim();
                        th.DVT = GetMaDonVi(r["DonVi"].ToString());
                    }
                }
            }
            if (hasChanges)
            {
                this.context.SubmitChanges();
                this.table.AcceptChanges();
                this.gvDmbd.DataSource = table;

                MessageBox.Show("Đã cập nhật xong.");
            }
            else
                MessageBox.Show("Không có thông tin thuốc nào được sữa.", "Thông báo");
        }

        private void ucBtThem_Click(object sender, EventArgs e)
        {
            DoInsert();
        }

        private void comboBoxEdit1_Properties_MouseDown(object sender, MouseEventArgs e)
        {
            
        }

        private void comboBoxEdit1_Properties_MouseDown_1(object sender, MouseEventArgs e)
        {
            
        }

        private void DoInsert() {
            var valResult = this.DoValidate();
            if (valResult == string.Empty)
            {
                Insert();
                ClearControls();
            }
            else
                MessageBox.Show(valResult);
        }

        private void ClearControls()
        {
            this.cbDVT.Text = "Viên";
            this.cbTenThuoc.Text = string.Empty;
            this.cbTenThuoc.Focus();
            this.mmGhiChu.Text = string.Empty;
        }

        private void Insert() 
        {
            var thuoc = new Thuoc
            {
                TenThuoc = this.cbTenThuoc.Text.Trim(),
                MoTa = this.mmGhiChu.Text.Trim(),
                DVT = GetMaDonVi(this.cbDVT.Text.Trim()),
                Dung = !cbkhongdung.Checked
            };
            this.context.Thuocs.InsertOnSubmit(thuoc);
            this.context.SubmitChanges();
            //add object to table
            var r = this.table.NewRow();
            r.ItemArray = new object[] { 
                thuoc.Id, thuoc.TenThuoc, thuoc.MoTa, this.cbDVT.Text.Trim(), thuoc.Dung.Value
            };
            this.table.Rows.Add(r);
            this.table.AcceptChanges();

            this.gvDmbd.DataSource = table;

        }

        private int GetMaDonVi(string tenDv)
        {
            var first = this.context.DonVis.FirstOrDefault(x => x.TenDonVi == tenDv);
            if (first != null)
                return first.Id;

            return 0;
        }

        private string DoValidate() {
            if (this.cbTenThuoc.Text.Trim() == string.Empty)
                return "Xin nhập tên thuốc";
            if (this.cbDVT.Text.Trim() == string.Empty)
                return "Xin nhập đơn vị tính";

            return string.Empty;
        }

        private void cbTenThuoc_Properties_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter) {
                DoInsert();
            }
        }

        private void cbDVT_Properties_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                DoInsert();
            }
        }

        private void mmGhiChu_Properties_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                DoInsert();
            }
        }
    }
}